package com.example.javaee.service;

import com.example.javaee.Util.CommunityUtil;
import com.example.javaee.Util.JwtTokenUtil;
import com.example.javaee.dao.UserMapper;
import com.example.javaee.domain.User;
import com.google.code.kaptcha.Producer;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Service
public class LoginService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    Producer kaptchaProducer;
//    @Autowired
//    private RedisTemplate redisTemplate;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    public void getKaptcha(HttpServletResponse response){
        // 生成验证码
        String text = kaptchaProducer.createText(); // 生成随机字符(验证码）
        //System.out.println("验证码：" + text);

        BufferedImage image = kaptchaProducer.createImage(text); // 生成图片
        response.setContentType("image/png");
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);
        try {
            ServletOutputStream outputStream=response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        }catch (IOException ignored){
        }

        // 将验证码存入 redis
//        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
//        redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS); //存入
       // redisTemplate.opsForValue().set(kaptchaOwner,text,60,TimeUnit.SECONDS);
    }


    public boolean login(String username,
                         String password)
    {
        User user=userMapper.selectByName(username);
        if(user==null){
            return false;
        }
        password=CommunityUtil.md5(password+user.getSalt());
        if(!user.getPassword().equals(password)){
//            System.out.println(password);
//            System.out.println(user.getPassword());
            return false;
        }
        System.out.println("loginsucess");
        return true;
    }

    /**
     * 获取当前登录用户基本信息对象
     */
    public User getLoginUser() {
        String token = this.getCurrentUserTokenReal();
        if (token != null) {
            return this.getUserFromToken(token);
        } else {
            return null;
        }
    }

    /**
     * 通过token解析用户信息对象
     */
    public User getUserFromToken(String token) {
        Claims claimFromToken = jwtTokenUtil.getClaimFromToken(token);
        String subject=claimFromToken.getSubject();
        return userMapper.getSomeUserInfo(subject);
    }


    /**
     * 获取当前请求下 请求头中的 Authorization 或者 请求参数中 token值
     */
    public String getCurrentUserTokenReal() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        String token;
        String authToken = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(authToken)) {
            return authToken;
        }
        token = request.getParameter("token");
        if (!StringUtils.isEmpty(token)) {
            return token;
        }
        return null;
    }

}
